package org.example.test_03.Config;
import com.alibaba.fastjson.JSON;
import org.example.test_03.Domian.ReturnData;
import org.example.test_03.utils.JWTUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义一个拦截器类,用来拦截所有请求
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 在这里会被拦截，否则放行
        if (handler instanceof HandlerMethod) {//是不是属于拦截的路径
            System.out.println(request.getRequestURL() + "这个方法被拦截");
            //设置请求内容的编码，防止乱码
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有域名跨域访问
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // 允许的请求方法
            response.setHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许的请求头
            //从 http 请求头中取出 token
            String token = request.getHeader("token");
            if (token == null || token.equals("")) {//不存在token,则告诉前端需要登录
                getJson(ReturnData.error("请先登录"), response);
                return false;
            } else {//如果存在 TOKEN
                String s = JWTUtil.checkToken(token);
                if(s!=null){
                    return true;
                }else{
                    getJson(ReturnData.error("token无效"), response);
                    return false;
                }

            }
        }
        return true;
    }

    public void getJson(Object object, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(JSON.toJSONString(object));
    }
}

